﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SuperCalculator
{
    public partial class frmAddUsing : Form
    {
        private StringCollection referenceAssemblyCollection = new StringCollection();//所有dll
        private StringCollection referenceNotSystemAssemblyCollection = new StringCollection();//非系统dll


        /// <summary>
        /// 获取引用的程序集的完整路径的集合
        /// </summary>
        public StringCollection ReferenceAssemblyCollection
        {
            get
            {
                return this.referenceAssemblyCollection;
            }
        }

        public frmAddUsing()
        {
            InitializeComponent();
        }

        private void frmAddUsing_Load(object sender, EventArgs e)
        {
            //读取.us文件中已有的using语句
            string path = Function.GetPathOfUsingFile();
            StreamReader sr = new StreamReader(path);
            try
            {
                while (sr.Peek() != -1)
                {
                    this.textBoxInput.Text += sr.ReadLine() + Environment.NewLine;
                }
            }
            catch
            {
            }
            finally
            {
                sr.Close();
            }

        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void buttonOk_Click(object sender, EventArgs e)
        {
            this.referenceAssemblyCollection.AddRange(this.FindDllFormTextBox());

            //修改编译单元的引用程序集
            CompilerUnit.ReferenceAssemblyCollection = this.referenceAssemblyCollection;

            //将某些引用程序集拷贝到当前目录下
            this.CopyReferenceAssemblyToStartupPath();

            //保存.us文件
            this.saveUsingFile();

            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 根据文本查找其中的using语句,然后返回对应的dll完整路径集合
        /// </summary>
        /// <param name="txt"></param>
        private string[] FindDllFormTextBox()
        {
            StringCollection sc = new StringCollection();

            //-------------------
            //根据using语句查找dll
            //-----------------
            foreach (string codeLine in this.textBoxInput.Lines)
            {
                string pattern = "(?<=using ).*(?=;)";

                MatchCollection matchs = Regex.Matches(codeLine, pattern);

                foreach (Match m in matchs)
                {
                    string dll = m.Value + ".dll";
                    /*
                     * 检查是否有对应的.dll文件，就是看公共语言运行库的安装目录下有没有对应的
                     * .dll文件,下面是用绝对路径检查文件是否存在,这比读取公共语言运行库的安装目录下所有
                     * 的.dll文件然后看是否有对应名称的dll要高效一些
                     */
                    if (File.Exists(RuntimeEnvironment.GetRuntimeDirectory() + Path.DirectorySeparatorChar + dll) ||
                        File.Exists(RuntimeEnvironment.GetRuntimeDirectory() + Path.DirectorySeparatorChar +
                                                 "zh-CHS" + Path.DirectorySeparatorChar + dll)//不可靠的"zh_CHS";
                        )
                    {
                        sc.Add(dll);
                    }
                }
            }

            string[] arr = new string[sc.Count];
            sc.CopyTo(arr, 0);
            return arr;
        }

        private void CopyReferenceAssemblyToStartupPath()
        {
            foreach (string sourceDll in referenceNotSystemAssemblyCollection)
            {
                try
                {
                    string dest = Function.DirectoryOfFunctions + Path.DirectorySeparatorChar + Path.GetFileName(sourceDll);
                    File.Copy(sourceDll, dest, true);
                }
                catch { }
            }
        }


        /// <summary>
        /// 将using 语句保存到文件.注意这里不保证语句的正确性,如果编译未通过请将该文件还原
        /// </summary>
        private void saveUsingFile()
        {
            StreamWriter sw = new StreamWriter(Function.GetPathOfUsingFile());
            try
            {
                foreach (string line in this.textBoxInput.Lines)
                {
                    sw.WriteLine(line + Environment.NewLine);
                }
            }
            catch { }
            finally
            {
                sw.Close();
            }
        }


        private void buttonView_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.InitialDirectory = RuntimeEnvironment.GetRuntimeDirectory();
            this.openFileDialog1.Multiselect = false;

            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string path = this.openFileDialog1.FileName;
                this.referenceAssemblyCollection.Add(path);
                this.referenceNotSystemAssemblyCollection.Add(path);

                //添加到listView
                string[] arr = new string[2];
                arr[0] = Path.GetFileName(path);
                arr[1] = path;
                ListViewItem lvi = new ListViewItem(arr);
                this.listView1.Items.Insert(0, lvi);
            }

        }

    }
}
